<template>
  <view class="container">
    <uni-nav-bar title="工作统计" left-icon="arrowleft" @clickLeft="goBack"></uni-nav-bar>
    
    <view class="filter-box">
      <picker mode="date" fields="month" @change="handleMonthChange">
        <view class="month-picker">{{ currentMonth }}</view>
      </picker>
    </view>
    
    <scroll-view scroll-y class="stats-container">
      <!-- 统计卡片 -->
      <view class="stats-card">
        <view class="stats-title">本月工作概览</view>
        <view class="stats-overview">
          <view class="overview-item">
            <text class="overview-value">{{ statsData.total_records || 0 }}</text>
            <text class="overview-label">总记录数</text>
          </view>
          <view class="overview-item">
            <text class="overview-value fee">¥{{ statsData.total_fee || 0 }}</text>
            <text class="overview-label">总费用</text>
          </view>
          <view class="overview-item">
            <text class="overview-value">{{ statsData.avg_fee ? Number(statsData.avg_fee).toFixed(2) : '0.00' }}</text>
            <text class="overview-label">平均费用</text>
          </view>
        </view>
      </view>
      
      <!-- 按日期统计 -->
      <view class="stats-card">
        <view class="stats-title">按日期统计</view>
        <view class="chart-container">
          <qiun-data-charts 
            v-if="hasDateStats"
            type="column" 
            :chartData="dateChartData" 
            :echartsH5="true" 
            :echartsApp="true" 
          />
          <view v-else class="no-data">暂无数据</view>
        </view>
      </view>
      
      <!-- 按类型统计 -->
      <view class="stats-card">
        <view class="stats-title">按集装箱类型统计</view>
        <view class="chart-container">
          <qiun-data-charts 
            v-if="hasTypeStats"
            type="pie" 
            :chartData="typeChartData" 
            :canvas2d="true"
            canvasId="typeChart"
          />
          <view v-else class="no-data">暂无数据</view>
        </view>
      </view>
      
      <!-- 按车辆统计 -->
      <view class="stats-card" v-if="hasCarStats">
        <view class="stats-title">按车辆统计</view>
        <view class="car-stats">
          <view class="car-item" v-for="item in statsData.car_stats" :key="item.car">
            <text class="car-name">{{ item.car || '未指定车辆' }}</text>
            <text class="car-count">{{ item.count }}次</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/store/work_api.js';
import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
export default {
	components: {
    qiunDataCharts
  },
  data() {
    return {
      currentMonth: this.formatDate(new Date(), 'YYYY-MM'),
      statsData: {
        date_stats: [],
        type_stats: [],
        car_stats: [],
        total_records: 0,
        total_fee: 0,
        avg_fee: 0
      },
      dateChartData: {
        categories: [],
        series: []
      },
      typeChartData: {
        categories: [],
        series: []
      }
    }
  },
  computed: {
    hasDateStats() {
      return this.statsData.date_stats && this.statsData.date_stats.length > 0;
    },
    hasTypeStats() {
      return this.statsData.type_stats && this.statsData.type_stats.length > 0;
    },
    hasCarStats() {
      return this.statsData.car_stats && this.statsData.car_stats.length > 0;
    }
  },
  onLoad() {
    this.loadStats();
  },
  methods: {
    formatDate(date, fmt) {
      const o = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    handleMonthChange(e) {
      this.currentMonth = e.detail.value;
      this.loadStats();
    },
    
    async loadStats() {
      uni.showLoading({
        title: '加载中...'
      });
      
      try {
        const [startDate, endDate] = this.getMonthRange(this.currentMonth);
        const res = await api.getStatistics({
          start_date: startDate,
          end_date: endDate
        });
        
        if (res.statusCode !== 200 || !res.data || res.data.status !== 'success') {
          throw new Error(res.data?.message || '加载统计失败');
        }
        
        const data = res.data.data;
        
        // 处理可能为null的fee_stats
        const feeStats = data.fee_stats || {
          total_fee: null,
          avg_fee: null,
          max_fee: null,
          min_fee: null
        };
        
        // 计算总记录数
        const totalRecords = this.calculateTotalRecords(data.date_stats);
        
        // 处理统计数据
        this.statsData = {
          date_stats: data.date_stats || [],
          type_stats: data.type_stats || [],
          car_stats: data.car_stats || [],
          total_records: totalRecords,
          total_fee: feeStats.total_fee || 0,
          avg_fee: feeStats.avg_fee || 0
        };
        
        // 更新图表数据
        this.updateCharts();
      } catch (err) {
        console.error('加载统计错误:', err);
        uni.showToast({
          title: err.message || '加载统计失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    calculateTotalRecords(dateStats) {
      if (!dateStats || !Array.isArray(dateStats)) return 0;
      return dateStats.reduce((total, item) => total + (item.count || 0), 0);
    },
    
    updateCharts() {
      // 日期统计图表
      if (this.hasDateStats) {
        this.dateChartData = {
          categories: this.statsData.date_stats.map(item => 
            item.date ? item.date.split('-')[2] + '日' : ''
          ),
          series: [{
            name: '数量',
            data: this.statsData.date_stats.map(item => item.count || 0),
            color: '#3498db'
          }]
        };
      } else {
        this.dateChartData = {
          categories: [],
          series: []
        };
      }
      
      // 类型统计图表
      if (this.hasTypeStats) {
        this.typeChartData = {
          series: [{
            data: this.statsData.type_stats.map(item => ({
              name: item.container_type || '未知',
              value: item.count || 0
            }))
          }]
        };
      } else {
        this.typeChartData = {
          series: []
        };
      }
    },
    
    getMonthRange(month) {
      const year = parseInt(month.split('-')[0]);
      const monthNum = parseInt(month.split('-')[1]);
      const startDate = new Date(year, monthNum - 1, 1);
      const endDate = new Date(year, monthNum, 0);
      
      return [
        this.formatDate(startDate, 'YYYY-MM-DD'),
        this.formatDate(endDate, 'YYYY-MM-DD')
      ];
    }
  }
}
</script>

<style>
/* 保持原有样式不变 */
.no-data {
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 28rpx;
}

.chart-container {
  width: 100%;
  height: 500rpx;
  position: relative;
}

.qiun-data-charts {
  width: 100%;
  height: 100%;
}

.month-picker {
  background-color: #f5f5f5;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  font-size: 30rpx;
}

.stats-container {
  flex: 1;
  padding: 20rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #eee;
}

.stats-overview {
  display: flex;
  justify-content: space-around;
  text-align: center;
  padding: 20rpx 0;
}

.overview-item {
  display: flex;
  flex-direction: column;
}

.overview-value {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.overview-value.fee {
  color: #e74c3c;
}

.overview-label {
  font-size: 24rpx;
  color: #666;
}

.car-stats {
  margin-top: 20rpx;
}

.car-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.car-name {
  font-size: 28rpx;
}

.car-count {
  font-size: 28rpx;
  color: #3498db;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.filter-box {
  padding: 20rpx;
  display: flex;
  justify-content: center;
}
</style>